package hivi.vn.hivigold.activities;

import hivi.vn.hivigold.R;
import hivi.vn.hivigold.adapters.GoldPriceAdapter;
import hivi.vn.hivigold.adapters.PriceLoader;
import hivi.vn.hivigold.database.Preferences;
import hivi.vn.hivigold.database.WebService;
import hivi.vn.hivigold.objects.Gold;
import hivi.vn.hivigold.utils.AccessDenied;
import hivi.vn.hivigold.utils.Formats;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class GoldPriceActivity extends FragmentActivity implements
		OnItemClickListener, LoaderCallbacks<ArrayList<Gold>> {
	GoldPriceAdapter adapter;
	EditText txtPriceBuy;
	EditText txtPriceSale;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.goldprice_layout);
		ListView lv = (ListView) findViewById(R.id.lstGoldPrice);
		adapter = new GoldPriceAdapter(this, null);
		lv.setAdapter(adapter);
		lv.setOnItemClickListener(this);
		getSupportLoaderManager().initLoader(1, null, this);
	}

	void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager) getBaseContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm != null)
		{
			imm.hideSoftInputFromWindow(txtPriceBuy.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(txtPriceSale.getWindowToken(), 0);
		}
			
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		if (!AccessDenied.KCB1) {
			Toast.makeText(this, R.string.warning_access_denied,
					Toast.LENGTH_LONG).show();
			return;
		}
		View v = this.getLayoutInflater().inflate(R.layout.price_layout, null);
		final TextView tvGoldName = (TextView) v.findViewById(R.id.tvPriceName);
		txtPriceBuy = (EditText) v
				.findViewById(R.id.txtBuy_price);
		txtPriceSale = (EditText) v
				.findViewById(R.id.txtSale_price);
		final Button btnSave = (Button) v.findViewById(R.id.btnSave);

		final Gold g = adapter.getGoldAtIndex(arg2);
		tvGoldName.setText(g.getTienteName());
		txtPriceBuy.setText(Formats.money(g.getMua_vao()));
		txtPriceSale.setText(Formats.money(g.getBan_ra()));
		txtPriceBuy.requestFocus();
		final Dialog dialog = new Dialog(this);
		btnSave.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				hideKeyboard();
				if (txtPriceBuy.getText().toString().trim().length() == 0
						|| txtPriceSale.getText().toString().trim().length() == 0) {
					Toast.makeText(getBaseContext(),
							R.string.warning_price_notempty, Toast.LENGTH_LONG)
							.show();
					return;
				}
				g.setBan_ra(Double.parseDouble(txtPriceSale.getText()
						.toString().replace(",", "")));
				g.setMua_vao(Double.parseDouble(txtPriceBuy.getText()
						.toString().replace(",", "")));
				g.setUser_id2(Preferences.getPreferenceValue(getBaseContext(),
						Preferences.USERID));
				dialog.dismiss();
				PriceTask pt = new PriceTask();
				pt.execute(g);
			}
		});
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.getWindow().setLayout(600, LayoutParams.WRAP_CONTENT);
		dialog.setContentView(v);
		dialog.show();
	}

	private class PriceTask extends AsyncTask<Gold, Void, Boolean> {
		ProgressDialog dialog;

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result) {
				Toast.makeText(getBaseContext(),
						R.string.alert_change_price_success, Toast.LENGTH_LONG)
						.show();
				 getSupportLoaderManager().getLoader(1).onContentChanged();
			} else {
				Toast.makeText(getBaseContext(),
						R.string.alert_change_price_fail, Toast.LENGTH_LONG)
						.show();
			}
			dialog.dismiss();
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog = new ProgressDialog(GoldPriceActivity.this);
			dialog.setMessage(getResources().getString(R.string.alert_waiting));
			dialog.show();
		}

		@Override
		protected Boolean doInBackground(Gold... g) {
			// TODO Auto-generated method stub
			return WebService.updateGoldPrice(getBaseContext(), g[0]);
		}
	}

	@Override
	public Loader<ArrayList<Gold>> onCreateLoader(int arg0, Bundle arg1) {
		// TODO Auto-generated method stub
		return new PriceLoader(this);
	}

	@Override
	public void onLoadFinished(Loader<ArrayList<Gold>> arg0,
			ArrayList<Gold> arg1) {
		// TODO Auto-generated method stub
		adapter.swaper(arg1);
	}

	@Override
	public void onLoaderReset(Loader<ArrayList<Gold>> arg0) {
		// TODO Auto-generated method stub
		adapter.swaper(null);
	}

	public static void onStartIntent(Context c)
	{
		Intent i = new Intent(c, GoldPriceActivity.class);
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		c.startActivity(i);
	}
	
}
